<!--集中式房型编辑表单-->
<template>
	<a-modal v-bind="options">
		<a-form ref="form" :model="roomType" layout="vertical" :rules="rules">
			<a-typography-paragraph strong>
				<blockquote>房型信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="16">
				<a-col :span="6">
					<a-form-item label="房型名称" name="name">
						<a-input v-model:value="roomType.name" allow-clear :maxlength="10" show-count placeholder="请输入房型名称" />
					</a-form-item>
				</a-col>
				<a-col :span="14">
					<a-form-item label="户型信息" name="apartment">
						<a-form-item-rest>
							<a-input-group compact style="display: flex">
								<a-input-number
									v-model:value="roomType.roomCount"
									:disabled="roomType?.talentedHouseStatus"
									:min="0"
									:precision="0"
									addon-after="室"
									placeholder="请输入"
									style="flex: 1" />
								<a-input-number
									v-model:value="roomType.hallCount"
									:disabled="roomType?.talentedHouseStatus"
									:min="0"
									:precision="0"
									addon-after="厅"
									placeholder="请输入"
									style="flex: 1" />
								<a-input-number
									v-model:value="roomType.toiletCount"
									:disabled="roomType?.talentedHouseStatus"
									:min="0"
									:precision="0"
									addon-after="卫"
									placeholder="请输入"
									style="flex: 1" />
								<a-input-number
									v-model:value="roomType.area"
									:min="0"
									:precision="2"
									addon-after="㎡"
									placeholder="请输入"
									style="flex: 1" />
							</a-input-group>
						</a-form-item-rest>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="装修类型" name="decorationTypeId">
						<a-select
							v-model:value="roomType.decorationTypeId"
							:options="fitmentTypes"
							:field-names="DEFAULT_FIELD_NAME"
							allow-clear
							show-search
							placeholder="请选择装修类型" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="朝向" name="orientation">
						<a-select
							v-model:value="roomType.orientation"
							:options="orientationList"
							allow-clear
							show-search
							placeholder="请选择朝向" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="出租价（元）：" name="rentalPrice">
						<a-input-number
							v-model:value="roomType.rentalPrice"
							:min="0"
							:precision="2"
							addon-after="元"
							@change="roomType.basePrice = roomType.rentalPrice"
							placeholder="请输入出租价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="底价（元）：" name="basePrice">
						<a-input-number
							v-model:value="roomType.basePrice"
							:min="0"
							:max="roomType.rentalPrice"
							:precision="2"
							addon-after="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="房型押金(元)：" name="depositPrice">
						<a-input-number
							v-model:value="roomType.depositPrice"
							:min="0"
							:precision="2"
							addon-after="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="房型物业费(元)：" name="propertyPrice">
						<a-input-number
							v-model:value="roomType.propertyPrice"
							:min="0"
							:precision="2"
							addon-after="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4" v-if="roomType.houseBizMode == 1">
					<a-form-item label="收房价（元）：" name="costPrice">
						<a-input-number
							v-model:value="roomType.costPrice"
							:min="0"
							:max="999999999.99"
							:precision="2"
							addon-after="元"
							placeholder="请输入收房价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="可住人数" name="userLimit">
						<a-input-number v-model:value="roomType.userLimit" :min="0" :precision="0" placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="可租日期：" name="avaliableDate">
						<a-date-picker
							v-model:value="roomType.avaliableDate"
							allow-clear
							:value-format="DATE_FORMAT.DATE"
							placeholder="请选择可租日期"
							style="width: 100%" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph>
				<strong><blockquote style="display: inline-block">房型特色</blockquote></strong>
				<!-- <a-col :xs="12" :sm="8" :md="6" :lg="4" :xl="3"> -->
				<a class="blockquote" @click="onClickToEditDic('HOUSE@TAGS', '添加房源特色')">
					<plus-circle-outlined />
					添加
				</a>
				<a-checkbox
					class="checkBox"
					:indeterminate="visibles.indeterminate"
					v-model:checked="visibles.characteristic"
					@change="changeCharacteristic">
					随机选10项
				</a-checkbox>
				<!-- </a-col> -->
			</a-typography-paragraph>
			<a-form-item name="tags">
				<a-checkbox-group v-model:value="roomType.tags">
					<a-row :gutter="16">
						<a-col v-for="item in tags" :key="item.id" :xs="12" :sm="8" :md="6" :lg="4">
							<a-checkbox :value="item.name" class="dic-edit-checkbox" @change="handler(item, 'HOUSE@TAGS')">
								{{ item.name }}
								<a @click.prevent="onClickToEditDic('HOUSE@TAGS', '编辑房源特色', item)">
									<edit-outlined />
								</a>
							</a-checkbox>
						</a-col>
						<!-- <a-col :xs="12" :sm="8" :md="6" :lg="4" :xl="3">
							<a @click="onClickToEditDic('HOUSE@TAGS', '添加房源特色')">
								<plus-circle-outlined />
								添加
							</a>
						</a-col> -->
					</a-row>
				</a-checkbox-group>
			</a-form-item>
			<a-typography-paragraph>
				<strong><blockquote style="display: inline-block">房型配置</blockquote></strong>
				<a class="blockquote" @click="onClickToEditDic('HOUSE@OUTFIT', '添加房源配置')">
					<plus-circle-outlined />
					添加
				</a>
				<a-checkbox v-if="configs.length !== 0" class="checkBox" :checked="visibles.dispose" @change="selectAll">全选</a-checkbox>
			</a-typography-paragraph>
			<a-form-item name="roomConfigs">
				<a-checkbox-group v-model:value="roomType.roomConfigs" style="width: 100%">
					<a-row :gutter="16">
						<a-col v-for="item in configs" :key="item.id" :xs="12" :sm="8" :md="6" :lg="4">
							<a-checkbox :value="item.id" class="dic-edit-checkbox">
								{{ item.name }}
								<a @click.prevent="onClickToEditDic('HOUSE@OUTFIT', '编辑房源配置', item)">
									<edit-outlined />
								</a>
							</a-checkbox>
						</a-col>
						<!-- <a-col :xs="12" :sm="8" :md="6" :lg="4" :xl="3">
							<a @click="onClickToEditDic('HOUSE@OUTFIT', '添加房源配置')">
								<plus-circle-outlined />
								添加
							</a>
						</a-col> -->
					</a-row>
				</a-checkbox-group>
			</a-form-item>
			<a-typography-paragraph strong>
				<blockquote>房源名称</blockquote>
			</a-typography-paragraph>
			<a-textarea v-model:value="roomType.title" :maxlength="30" show-count placeholder="请输入房型名称" />
			<a-typography-paragraph strong>
				<blockquote>房型描述</blockquote>
			</a-typography-paragraph>
			<a-form-item name="introduction">
				<a-textarea v-model:value="roomType.introduction" :maxlength="300" show-count placeholder="请输入房型描述" />
			</a-form-item>
			<a-typography-paragraph strong>
				<blockquote>VR看房地址</blockquote>
			</a-typography-paragraph>
			<a-form-item name="vrUrl">
				<a-input v-model:value="roomType.vrUrl" type="url" :maxlength="500" show-count allow-clear placeholder="请输入VR看房地址" />
			</a-form-item>
			<a-typography-paragraph strong>
				<blockquote>房型图片</blockquote>
			</a-typography-paragraph>
			<a-form-item name="imgList">
				<file-upload
					v-model:files="roomType.imgList"
					:biz-id="roomType.id"
					:limit="24"
					accept=".jpg,.png,.jpeg"
					sub-type="houseImageTypes" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button type="primary" :loading="loading.save" @click="saveRoomType">保存</a-button>
		</template>
	</a-modal>

	<dic-edit-dialog v-model:visible="visibles.dic" :value="dic" @close="getDics" />
</template>

<script lang="ts" setup>
	import {reactive, ref, toRef, watchEffect, watch} from 'vue'
	import {RoomType} from '@/interface/community'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {Dic} from 'yuxin-base/src/types'
	import {DEFAULT_FIELD_NAME, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {FormInstance, message} from 'ant-design-vue'
	import {EditOutlined, PlusCircleOutlined} from '@ant-design/icons-vue'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {orientationList} from '@/interface/house'
	import houseApi from '@/api/house-api'
	import {roomTypeRules} from '@/rules/community'
	import FileUpload from '@/components/common/file-upload.vue'
	import DicEditDialog from '@/components/common/dic-edit-dialog.vue'
	import {useStore} from '@/store/index'
	import {number} from 'vue-types'
	import {computed} from 'vue'
	const hasPermissions = useStore().hasPermissions
	const rules = ref({})
	const props = defineProps<{
		visible: boolean
		value?: RoomType
	}>()

	const loading = reactive<any>({
		save: false,
		load: false
	})

	const visibles = reactive<any>({
		dic: false,
		characteristic: false,
		dispose: computed(() => {
			return configs.value.length === props.value?.roomConfigs?.length && configs.value.length !== 0
		}),
		indeterminate: false
	})
	const timeNumber = ref<any>(null)

	const form = ref<FormInstance>()
	const roomType = ref<RoomType>({})
	// watchEffect(() => {
	// 	if (props.visible) {
	// 		// 获取字典
	// 		getDics()
	// 		roomType.value = props.value || {}
	// 		// 配置回显
	// 		roomType.value.roomConfigs = (roomType.value.roomCfgList || []).map((c: any) => c.id)
	// 	} else {
	// 		form.value?.resetFields()
	// 	}
	// })
	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				if (props.value?.id) {
					options.title = '编辑房型'
				} else {
					options.title = '添加房型'
				}

				getDics()
				// 获取字典
				roomType.value = props.value || {}

				// 配置回显
				roomType.value.roomConfigs = (roomType.value.roomCfgList || []).map((c: any) => c.id)
				timeNumber.value = setTimeout(() => {
					isSelectAll()
					clearTimeout(timeNumber.value)
				}, 300)
				rules.value = {
					...rules.value,
					...roomTypeRules(roomType.value)
				}
			} else {
				form.value?.resetFields()
			}
		}
	)
	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		width: 1100,
		title: '添加房型',
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		class: 'room-type-edit-dialog',
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	// 装修类型字典
	const fitmentTypes = ref<Dic[]>([])
	// 特色类型字典
	const tags = ref<Dic[]>([])
	// 配置类型字典
	const configs = ref<Dic[]>([])

	const getDics = async () => {
		// 82308字典修改 新增查使用中 编辑查全部
		let action = props.value?.id ? settingApi.getDicListByPidAll : settingApi.getDicListByPid
		action(DIC_PID_MAP['HOUSE@DECORTYPE']).then(({data}) => (fitmentTypes.value = data))

		settingApi.getDicListByPid(DIC_PID_MAP['HOUSE@TAGS']).then(({data}) => (tags.value = data))
		settingApi.getDicListByPid(DIC_PID_MAP['HOUSE@OUTFIT']).then(({data}) => (configs.value = data))
		//todo
		const res = await settingApi.getDecisionList({bizPoint: 'HOUSE_SETTING', module: 'HOUSE'})
		let source = JSON.parse(res.data[0]?.value || '[]')
		console.log(111);

		if(source.includes(1)) rules.value.depositPrice = [{required: true, message: '请输入押金'}]
		if(source.includes(2)) rules.value.propertyPrice = [{required: true, message: '请输入物业费'}]

	}

	/**
	 * 添加字典
	 */
	const dic = ref<Dic>()
	const onClickToEditDic = (label: string, title: string, item?: any) => {
		visibles.dic = true
		dic.value = {
			label,
			title,
			isUse: 1,
			...item,
			pid: DIC_PID_MAP[label]
		}
	}

	/**
	 * 保存房型模板信息
	 */
	const saveRoomType = () => {
		form.value
			?.validate()
			.then(async () => {
				// 82308字典修改
				if (roomType.value?.id && (await isDisabledF())) return

				loading.save = true
				roomType.value.imgIdList = (roomType.value.imgList || []).map(o => o.id) as []
				roomType.value.roomCfgList = configs.value.filter(o => roomType.value.roomConfigs?.includes(o.id as string))
				houseApi[roomType.value?.id ? 'updateRoomType' : 'createRoomType'](roomType.value)
					.then(() => {
						options.onCancel()
						message.success('保存成功')
					})
					.finally(() => (loading.save = false))
			})
			.catch(({errorFields}) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	// 随机选10项
	const arr = ref<any>([])
	const maxNum = ref(0)
	const changeCharacteristic = () => {
		roomType.value.tags = []
		arr.value = []
		if (tags.value.length > 10) {
			maxNum.value = 10
		} else {
			maxNum.value = tags.value.length
		}

		if (visibles.characteristic) {
			for (var i = 0; i < maxNum.value; i++) {
				let randomNum = getRandomNum(0, tags.value.length - 1)
				if (arr.value.findIndex((e: any) => e === randomNum) === -1) {
					arr.value.push(randomNum)
				} else {
					maxNum.value += 1
				}
			}
			arr.value.forEach(e => {
				roomType.value.tags?.push(tags.value[e].name as string)
				// tags.value[e].isSystemDefault = 1
			})
		} else {
			// arr.value.forEach(e => (tags.value[e].isSystemDefault = null))
			roomType.value.tags = []
		}
	}
	//随机数生成函数
	const getRandomNum = (min, max) => {
		return Math.floor(Math.random() * (max - min + 1) + min)
	}

	const selectAll = ({target: {checked}}) => {
		if (checked) {
			roomType.value.roomConfigs = configs.value.map((e: any) => e.id)
		} else {
			roomType.value.roomConfigs = []
		}
	}

	const handler = (data, filed) => {
		switch (filed) {
			case 'HOUSE@TAGS':
				console.log(roomType.value.tags.length, data)
				if (roomType.value.tags?.findIndex((e: any) => e === data.name) === -1 && roomType.value.tags.length + 1 >= 10) {
					visibles.characteristic = true
				} else if (roomType.value.tags?.findIndex((e: any) => e === data.name) !== -1 && roomType.value.tags.length - 1 >= 10) {
					visibles.characteristic = true
				} else {
					visibles.characteristic = false
				}
				break
		}
	}

	const isSelectAll = () => {
		// 房型特色
		if (tags.value.length > 10) {
			if (props.value?.tags?.length === 10) {
				visibles.characteristic = true
			} else {
				visibles.characteristic = false
			}
		} else {
			if (props.value?.tags?.length === tags.value.length) {
				visibles.characteristic = true
			} else {
				visibles.characteristic = false
			}
		}
		// 房型配置
		// if (configs.value.length === props.value?.roomConfigs?.length) {
		// 	visibles.dispose = true
		// } else {
		// 	visibles.dispose = false
		// }
	}
	/* 判断选择的字典是否被禁用 */
	// / 82308字典修改
	const isDisabledF = async () => {
		let temp = false
		let typesList: any = []
		typesList = await settingApi.getDicListByPid(DIC_PID_MAP['HOUSE@DECORTYPE'])
		if (typesList.data?.every((e: any) => e?.id !== roomType.value.decorationTypeId)) {
			temp = true
			return message.error('选项已禁用，请选择其他选项！')
		}
		return temp
	}
</script>

<style lang="less">
	.room-type-edit-dialog {
		.ant-modal-body {
			padding: 16px 16px 0;
			overflow: auto;
			min-height: 300px;
			max-height: 600px;
			height: 70vh;

			.ant-checkbox-group {
				display: block;

				.dic-edit-checkbox span + span > a {
					display: none;
				}

				.dic-edit-checkbox:hover span + span > a {
					display: inline;
				}
			}
		}
	}
	.blockquote {
		margin: 0 10px;
	}
	.checkBox {
		span {
			font-weight: 400;
			color: rgba(0, 0, 0, 0.85);
		}
	}
</style>
